const app = getApp()
import CommandManager from '../../../utils/commandManager'

Page({
  data: {
    wifiConfig: {
      ssid: '',
      password: ''
    },
    mqttConfig: {
      url: '',
      username: '',
      password: '',
      clientId: '',
      upTopic: '',
      downTopic: '',
      otaTopic: ''
    },
    otaConfig: {
      updateUrl: ''
    },
    isLoading: false,
    hasChanges: false
  },

  onLoad() {
    this.loadConfig()
  },

  // 加载配置
  loadConfig() {
    try {
      console.log('[配置] 加载全局配置:', app.globalData.wifiConfig, app.globalData.mqttConfig, app.globalData.otaConfig)
      this.setData({
        wifiConfig: app.globalData.wifiConfig ? app.globalData.wifiConfig : {
          ssid: '',
          password: ''
        },
        mqttConfig: app.globalData.mqttConfig ? app.globalData.mqttConfig : {
          url: '',
          username: '',
          password: '',
          clientId: '',
          upTopic: '',
          downTopic: '',
          otaTopic: ''
        },
        otaConfig: app.globalData.otaConfig ? app.globalData.otaConfig : {
          updateUrl: ''
        }
      })

      // 如果设备已连接，尝试获取设备当前配置
      if (app.globalData.udpManager && app.globalData.udpManager.isConnected) {
        this.queryDeviceConfig()
      }
    } catch (error) {
      console.error('[配置] 加载配置失败:', error)
      wx.showToast({
        title: '加载配置失败',
        icon: 'none'
      })
    }
  },

  // 查询设备当前配置
  queryDeviceConfig() {
    const frame = CommandManager.createCommand('QUERY_CONFIG')
    if (!frame) {
      console.error('[配置] 创建查询命令失败')
      return
    }
    console.log('[配置] 发送查询命令:', frame)

    wx.showLoading({
      title: '读取配置中...',
      mask: true
    })

    // 设置超时处理
    const timeout = setTimeout(() => {
      wx.hideLoading()
      wx.showToast({
        title: '读取超时',
        icon: 'none'
      })
    }, 2000) // 2秒超时

    app.globalData.udpManager.sendAndWait(frame, 2000)
      .then(response => {
        clearTimeout(timeout)
        console.log('[配置] 原始响应数据:', response)
        
        // 检查响应数据结构
        if (!response || response.length < 5) {
          throw new Error('响应数据格式错误')
        }

        try {
          // 解析响应帧
          const result = CommandManager.parseFrame(response)
          if (!result || !result.data) {
            throw new Error('响应数据格式错误')
          }

          console.log('[配置] 解析后的设备配置:', result.data)

          // 验证必要字段
          const requiredFields = ['ssid', 'pwd', 'mqtt_url', 'mqtt_client_id', 'mqtt_up_topic', 'mqtt_down_topic']
          const missingFields = requiredFields.filter(field => !result.data[field])
          
          if (missingFields.length > 0) {
            throw new Error(`缺少必要字段: ${missingFields.join(', ')}`)
          }
          
          // 更新配置数据
          this.setData({
            wifiConfig: {
              ssid: result.data.ssid || '',
              password: result.data.pwd || ''
            },
            mqttConfig: {
              url: result.data.mqtt_url || '',
              username: result.data.mqtt_username || '',
              password: result.data.mqtt_pwd || '',
              clientId: result.data.mqtt_client_id || '',
              upTopic: result.data.mqtt_up_topic || '',
              downTopic: result.data.mqtt_down_topic || '',
              otaTopic: result.data.mqtt_ota_topic || ''
            },
            otaConfig: {
              updateUrl: result.data.ota_server_url || ''
            }
          })

          // 保存配置到全局变量
          app.globalData.wifiConfig = this.data.wifiConfig
          app.globalData.mqttConfig = this.data.mqttConfig
          app.globalData.otaConfig = this.data.otaConfig

          console.log('[配置] 配置数据加载完成')
          wx.hideLoading()
        } catch (error) {
          console.error('[配置] 数据解析错误:', error)
          console.error('[配置] 原始数据:', response)
          wx.hideLoading()
          wx.showToast({
            title: error.message || '配置数据解析失败',
            icon: 'none'
          })
        }
      })
      .catch(err => {
        clearTimeout(timeout)
        console.error('[配置] 查询失败:', err)
        wx.hideLoading()
        wx.showToast({
          title: err.message || '读取配置失败',
          icon: 'none'
        })
      })
  },

  // 输入变化处理
  onInputChange(e) {
    const { section, field } = e.currentTarget.dataset
    const value = e.detail.value.trim()
    const oldValue = this.data[section][field]

    // 只有当值真正改变时才设置hasChanges
    if (value !== oldValue) {
      this.setData({
        [`${section}.${field}`]: value,
        hasChanges: true
      })
    } else {
      this.setData({
        [`${section}.${field}`]: value
      })
    }
  },

  // 验证MQTT URL格式
  isValidMqttUrl(url) {
    // 使用正则表达式验证MQTT URL
    const mqttUrlPattern = /^mqtt(s)?:\/\/[^\s/$.?#].[^\s]*$/i;
    return mqttUrlPattern.test(url);
  },

  // 验证URL格式
  isValidUrl(url) {
    // 使用正则表达式验证URL格式
    const urlPattern = /^https?:\/\/[^\s/$.?#].[^\s]*$/i;
    return urlPattern.test(url);
  },

  // 验证配置
  validateConfig() {
    const { wifiConfig, mqttConfig, otaConfig } = this.data

    // 验证WiFi配置
    if (!wifiConfig.ssid) {
      wx.showToast({
        title: '请输入WiFi名称',
        icon: 'none'
      })
      return false
    }

    // 验证MQTT配置
    if (!mqttConfig.url) {
      wx.showToast({
        title: '请输入MQTT服务器URL',
        icon: 'none'
      })
      return false
    }

    if (!this.isValidMqttUrl(mqttConfig.url)) {
      wx.showToast({
        title: '请输入有效的MQTT URL',
        icon: 'none'
      })
      return false
    }

    if (!mqttConfig.clientId) {
      wx.showToast({
        title: '请输入客户端ID',
        icon: 'none'
      })
      return false
    }

    if (!mqttConfig.upTopic) {
      wx.showToast({
        title: '请输入上行主题',
        icon: 'none'
      })
      return false
    }

    if (!mqttConfig.downTopic) {
      wx.showToast({
        title: '请输入下行主题',
        icon: 'none'
      })
      return false
    }

    // 验证OTA配置
    if (otaConfig.updateUrl && !this.isValidUrl(otaConfig.updateUrl)) {
      wx.showToast({
        title: '请输入有效的更新地址',
        icon: 'none'
      })
      return false
    }

    return true
  },

  // 验证OTA URL格式
  isValidOtaUrl(url) {
    // 允许http://和https://开头的URL,支持IP地址和端口号
    const otaUrlPattern = /^https?:\/\/(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])(:\d+)?(\/.*)?$/;
    return otaUrlPattern.test(url);
  },

  // 保存配置
  async saveConfig() {
    if (this.data.isLoading) {
      return;
    }

    // 验证配置
    if (!this.validateConfig()) {
      return;
    }

    try {
      this.setData({ isLoading: true });

      wx.showLoading({
        title: '保存中...',
        mask: true
      });

      // 更新全局状态
      app.globalData.wifiConfig = this.data.wifiConfig;
      app.globalData.mqttConfig = this.data.mqttConfig;
      app.globalData.otaConfig = this.data.otaConfig;

      // 发送配置到设备
      if (app.globalData.udpManager && app.globalData.udpManager.isConnected) {
        await this.sendConfigToDevice();
      }

      this.setData({ 
        hasChanges: false,
        isLoading: false
      });

      wx.hideLoading();
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      });

      // 延迟返回
      setTimeout(() => {
        wx.navigateBack();
      }, 2000);

    } catch (error) {
      console.error('[配置] 保存失败:', error);
      this.setData({ isLoading: false });
      
      wx.hideLoading();
      wx.showToast({
        title: error.message || '保存失败',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 发送配置到设备
  async sendConfigToDevice() {
    if (!app.globalData.udpManager || !app.globalData.udpManager.isConnected) {
      throw new Error('设备未连接')
    }

    // 构造与查询配置相同格式的数据结构
    const config = {
      ssid: this.data.wifiConfig.ssid,
      pwd: this.data.wifiConfig.password,
      mqtt_url: this.data.mqttConfig.url,
      mqtt_username: this.data.mqttConfig.username,
      mqtt_pwd: this.data.mqttConfig.password,
      mqtt_client_id: this.data.mqttConfig.clientId,
      mqtt_up_topic: this.data.mqttConfig.upTopic,
      mqtt_down_topic: this.data.mqttConfig.downTopic,
      mqtt_ota_topic: this.data.mqttConfig.otaTopic,
      ota_server_url: this.data.otaConfig.updateUrl
    }

    const frame = CommandManager.createCommand('SET_CONFIG', config)
    if (!frame) {
      throw new Error('创建配置命令失败')
    }

    try {
      // 发送配置并等待响应
      const response = await app.globalData.udpManager.sendAndWait(frame, 2000)  // 2秒超时
      
      // 解析响应
      const result = CommandManager.parseFrame(response)
      console.log('[配置] 设备返回结果:', result)
      
      // 检查返回结果，设备返回 {success: true} 表示成功
      if (!result || !result.data || !result.data.success) {
        throw new Error('设备返回错误')
      }
      
      console.log('[配置] 设备已接收配置')
    } catch (error) {
      console.error('[配置] 发送配置失败:', error)
      if (error.message.includes('timeout')) {
        throw new Error('保存超时')
      } else {
        throw new Error('发送配置失败，请重试')
      }
    }
  },

  // 页面卸载前确认
  onUnload() {
    if (this.data.hasChanges) {
      wx.showModal({
        title: '提示',
        content: '配置已修改但未保存，是否保存？',
        success: (res) => {
          if (res.confirm) {
            this.saveConfig()
          }
        }
      })
    }
  },

  onWifiSsidInput(e) {
    this.setData({
      'wifiConfig.ssid': e.detail.value,
      hasChanges: true
    });
  },

  onWifiPasswordInput(e) {
    this.setData({
      'wifiConfig.password': e.detail.value,
      hasChanges: true
    });
  },

  onMqttUrlInput(e) {
    this.setData({
      'mqttConfig.url': e.detail.value,
      hasChanges: true
    });
  },

  onMqttUsernameInput(e) {
    this.setData({
      'mqttConfig.username': e.detail.value,
      hasChanges: true
    });
  },

  onMqttPasswordInput(e) {
    this.setData({
      'mqttConfig.password': e.detail.value,
      hasChanges: true
    });
  },

  onMqttClientIdInput(e) {
    this.setData({
      'mqttConfig.clientId': e.detail.value,
      hasChanges: true
    });
  },

  onMqttUpTopicInput(e) {
    this.setData({
      'mqttConfig.upTopic': e.detail.value,
      hasChanges: true
    });
  },

  onMqttDownTopicInput(e) {
    this.setData({
      'mqttConfig.downTopic': e.detail.value,
      hasChanges: true
    });
  },

  onMqttOtaTopicInput(e) {
    this.setData({
      'mqttConfig.otaTopic': e.detail.value,
      hasChanges: true
    });
  },
}) 